package ass.dao.support;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import ass.beans.MovieBean;
import ass.beans.UserBean;
import ass.common.DBConnectionFactory;
import ass.common.ServiceLocatorException;
import ass.dao.DataAccessException;
import ass.dao.MovieDAO;

/**
 * The Data Access Object for Movies. This object performs the database
 * operations required for maintaining Movies.
 */
public class MovieDAOImpl implements MovieDAO {

	/**
	 * The service locator to retrieve database connections from
	 */
	private DBConnectionFactory services;

	/** Creates a new instance of MovieDAOImpl */
	public MovieDAOImpl() {
		try {
			services = new DBConnectionFactory();
		} catch (ServiceLocatorException e) {
			e.printStackTrace();
		}
	}

	public MovieDAOImpl(DBConnectionFactory services) {
		this.services = services;
	}

	public void insert(MovieBean bean) throws DataAccessException {
		Connection con = null;
		try {
			con = services.createConnection();
			PreparedStatement stmt = con
					.prepareStatement("insert into TBL_MOVIES (MOVIE_TITLE,MOVIE_SYNOPSIS,MOVIE_FROM_DATE,MOVIE_TO_DATE,MOVIE_POSTER,MOVIE_GENRE,MOVIE_DIRECTOR,MOVIE_AGE,MOVIE_ACTOR,MOVIE_ACTOR2,MOVIE_SHOWING_TIME,MOVIE_RATING) values (?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?)");
			stmt.setString(1, bean.getMovie_title());
			stmt.setString(2, bean.getMovie_synopsis());
			stmt.setDate(3, bean.getMovie_from_date());
			stmt.setDate(4, bean.getMovie_to_date());
			stmt.setBytes(5, bean.getMovie_poster());
			stmt.setString(6, bean.getMovie_genre());
			stmt.setString(7, bean.getMovie_director());
			stmt.setString(8, bean.getMovie_age());
			stmt.setString(9, bean.getMovie_actor());
			stmt.setString(10, bean.getMovie_actor2());
			stmt.setFloat(11, bean.getMovie_showing_time());
			stmt.setInt(12, bean.getMovie_rating());
			int n = stmt.executeUpdate();

			stmt.close();
			if (n != 1)
				throw new DataAccessException(
						"Did not insert one row into database");
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	/**
	 * @todo Complete this method
	 * @see com.enterprise.dao.MovieDAO#delete(int)
	 */
	public void delete(int id) throws DataAccessException {
		// TODO get the connection
		// TODO create a prepared statement
		// TODO set the id
		// TODO execute the statement
		// TODO catch and throw all the required exceptions
		// TODO close connections
	}
	
	public void update_rating(int id, int rating)  throws DataAccessException {
		
		Connection con = null;
		   try {
			    con = services.createConnection();
				String sql = "UPDATE TBL_MOVIES "+
							 "SET "+
							"	MOVIE_RATING = " +     rating + " "+
							" WHERE movie_id = ?";
				System.out.println(sql);
				
	            PreparedStatement stmt = con.prepareStatement(sql.toString());
	            // run the SQL statement
	            stmt.setInt(1, id);
	            int result = stmt.executeUpdate();
	            if (result == 0) {
	                System.out.println("Customer not updated.");
	            } else {
	                System.out.println("Customer updated.");
	            }
	            stmt.close();
		   } catch (ServiceLocatorException e) {
				throw new DataAccessException("Unable to retrieve connection; " + e.getMessage(), e);
		   } catch (SQLException e) {
				throw new DataAccessException("Unable to execute query; " + e.getMessage(), e);
		   } finally {
				if (con != null) {
					try {
						con.close();
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
	}

	/**
	 * @todo Complete the operation
	 * @see com.enterprise.dao.MovieDAO#findAllForUser(int)
	 */
	public List<MovieBean> getMovieByRangeDate(String from, String to)
			throws DataAccessException {
		List<MovieBean> list = new ArrayList<MovieBean>();
		Connection con = null;
		try {
			con = services.createConnection();
			// convert('2003-07-08',DATE)
			PreparedStatement stmt = con
					.prepareStatement("select * from TBL_MOVIES where  movie_from_date <= convert(?,DATE) and movie_to_date >= convert(?,DATE)  order by movie_rating desc ");
			stmt.setString(1, from);
			stmt.setString(2, to);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				MovieBean movieBean = createMovieBean(rs);
				list.add(movieBean);
			}
			stmt.close();
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}

		return list;
	}

	public List<MovieBean> getMovieComingSoon(String from)
			throws DataAccessException {
		List<MovieBean> list = new ArrayList<MovieBean>();
		Connection con = null;
		try {
			con = services.createConnection();
			// convert('2003-07-08',DATE)
			PreparedStatement stmt = con
					.prepareStatement("select * from TBL_MOVIES where  movie_from_date > convert(?,DATE) order by movie_from_date asc ");
			stmt.setString(1, from);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				MovieBean movieBean = createMovieBean(rs);
				list.add(movieBean);
			}
			stmt.close();
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}

		return list;
	}

	/**
	 * @todo Complete this method
	 * @see com.enterprise.dao.MovieDAO#getMovie(int)
	 */
	public MovieBean getMovieByTitle(String movietitle, String yearFrom,
			String yearTo) throws DataAccessException {
		Connection con = null;
		try {
			con = services.createConnection();
			PreparedStatement stmt = con
					.prepareStatement("select * from TBL_MOVIES where MOVIE_TITLE = ? and to_char(movie_from_date,'YYYY') between '?' and '?' ");
			stmt.setString(1, movietitle);
			stmt.setString(2, yearFrom);
			stmt.setString(3, yearTo);
			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				MovieBean movie = createMovieBean(rs);
				stmt.close();
				return movie;
			}
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

	public MovieBean getMovieByTitle(String movietitle)
			throws DataAccessException {
		Connection con = null;
		try {
			con = services.createConnection();
			PreparedStatement stmt = con
					.prepareStatement("select * from TBL_MOVIES where MOVIE_TITLE = ?");
			stmt.setString(1, movietitle);
			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				MovieBean movie = createMovieBean(rs);
				stmt.close();
				return movie;
			}
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

	public MovieBean getMovieByActor(String actor, String yearFrom,
			String yearTo) throws DataAccessException {
		Connection con = null;
		try {
			con = services.createConnection();
			PreparedStatement stmt = con
					.prepareStatement("select * from TBL_MOVIES where MOVIE_ACTOR = ? and to_char(movie_from_date,'YYYY') between '?' and '?' ");
			stmt.setString(1, actor);
			stmt.setString(2, yearFrom);
			stmt.setString(3, yearTo);
			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				MovieBean movie = createMovieBean(rs);
				stmt.close();
				return movie;
			}
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

	private MovieBean createMovieBean(ResultSet rs) throws SQLException {

		// MOVIE_ID INTEGER NOT NULL,
		// MOVIE_TITLE VARCHAR(200),
		// MOVIE_SYNOPSIS VARCHAR(4000),
		// MOVIE_FROM_DATE DATE,
		// MOVIE_TO_DATE DATE,
		// MOVIE_POSTER BINARY(2147483647),
		// MOVIE_GENRE VARCHAR(100),
		// MOVIE_DIRECTOR VARCHAR(100),
		// MOVIE_AGE VARCHAR(3),
		// MOVIE_ACTOR VARCHAR(100),
		// MOVIE_ACTOR2 VARCHAR(100),
		// MOVIE_SHOWING_TIME FLOAT(17),
		// MOVIE_RATING INTEGER

		MovieBean movieBean = new MovieBean();

		movieBean.setMovie_id(rs.getInt("movie_id"));
		movieBean.setMovie_title(rs.getString("movie_title"));
		movieBean.setMovie_synopsis(rs.getString("movie_synopsis"));
		movieBean.setMovie_from_date(rs.getDate("movie_from_date"));
		movieBean.setMovie_to_date(rs.getDate("movie_to_date"));
		movieBean.setMovie_genre(rs.getString("movie_genre"));
		movieBean.setMovie_director(rs.getString("movie_director"));
		movieBean.setMovie_age(rs.getString("movie_age"));
		movieBean.setMovie_director(rs.getString("movie_director"));
		movieBean.setMovie_actor(rs.getString("movie_actor"));
		movieBean.setMovie_actor2(rs.getString("movie_actor2"));
		movieBean.setMovie_showing_time(rs.getFloat("movie_showing_time"));
		movieBean.setMovie_rating(rs.getInt("movie_rating"));
		// movieBean.setMovie_poster(rs.getDate("movie_to_date") );

		return movieBean;
	}

	public MovieBean getMovie(int id) throws DataAccessException {
		Connection con = null;
		try {
			con = services.createConnection();
			PreparedStatement stmt = con
					.prepareStatement("select * from TBL_MOVIES where movie_id = ? ");
			stmt.setInt(1, id);
			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				MovieBean movie = createMovieBean(rs);
				stmt.close();
				return movie;
			}
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

	public List<MovieBean> getMovie(String title, String actor, String genre,
			String yearFrom, String yearTo) throws DataAccessException {
		List<MovieBean> list = new ArrayList<MovieBean>();
		Connection con = null;
		try {
			con = services.createConnection();

			PreparedStatement stmt = con
					.prepareStatement(" select * from ("
							+ " select * from tbl_movies where lower(movie_title) like lower('%'||?||'%')"
							+ " intersect"
							+ " select * from tbl_movies where lower(movie_genre) like lower('%'||?||'%')"
							+ " intersect"
							+ " select * from tbl_movies where lower(movie_actor) like lower('%'||?||'%')"
							+ " ) where to_char(movie_from_date,'YYYY') between ? and ? ");

			if (title == null) {
				title = "%";
			}
			if (actor == null) {
				actor = "%";
			}
			if (genre == null) {
				genre = "%";
			}

			stmt.setString(1, title);
			stmt.setString(2, genre);
			stmt.setString(3, actor);
			stmt.setString(4, yearFrom);
			stmt.setString(5, yearTo);

			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				MovieBean movieBean = createMovieBean(rs);
				list.add(movieBean);
			}
			stmt.close();
		} catch (ServiceLocatorException e) {
			throw new DataAccessException("Unable to retrieve connection; "
					+ e.getMessage(), e);
		} catch (SQLException e) {
			throw new DataAccessException("Unable to execute query; "
					+ e.getMessage(), e);
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}

		return list;
	}

}
